﻿using Anley.DomainDrivenDesign.Contract.Extension;
using Anley.DomainDrivenDesign.Contract.Helper;

namespace Anley.DomainDrivenDesign.Contract.Infrastructure;

/// <summary>
/// SqlServer仓储上下文提供程序类
/// </summary>
public class SqlServerRepositoryContextProvider
    : IDbRepositoryContextProvider
{
    private static string _connectionStringName = AneConsts.DefaultDbConnectionStringName;

    // 数据库连接字符串名称
    public string ConnectionStringName => _connectionStringName;

    // 设置数据库连接字符串名称
    public static void SetConnectionStringName(
        string connectionStringName)
    {
        _connectionStringName = connectionStringName;
    }

    // 获取仓储上下文
    public IDbRepositoryContext GetRepositoryContext()
    {
        var configuration = ServiceProviderHelper.ServiceProvider.GetRequiredService<IConfiguration>();
        var connectionString = configuration.GetConnectionString(ConnectionStringName);
        return new SqlServerRepositoryContext(connectionString.NotNullOrWhiteSpace(nameof(connectionString)));
    }
}